<template>
    <div class="config-wrapper">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="180px" @submit.native.prevent>
            <el-row :gutter="30">
                <el-col :span="12">
                    <h2 style="margin-bottom:16px;">量/次配置</h2>
                    <el-form-item label="普通跨应用分钟数" prop="regular_feature_minutes">
                        <el-input v-model.number="form.regular_feature_minutes" type="number" min="0"
                            @input="intInput('regular_feature_minutes')" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="会员跨应用分钟数" prop="member_feature_minutes">
                        <el-input v-model.number="form.member_feature_minutes" type="number" min="0"
                            @input="intInput('member_feature_minutes')" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="普通图片翻译" prop="regular_photos_limit">
                        <el-input v-model.number="form.regular_photos_limit" type="number" min="0"
                            @input="intInput('regular_photos_limit')" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="会员图片翻译" prop="member_photos_limit">
                        <el-input v-model.number="form.member_photos_limit" type="number" min="0"
                            @input="intInput('member_photos_limit')" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="普通网页翻译tokens" prop="regular_tokens_limit">
                        <el-input v-model.number="form.regular_tokens_limit" type="number" min="0"
                            @input="intInput('regular_tokens_limit')" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="会员网页翻译tokens" prop="member_tokens_limit">
                        <el-input v-model.number="form.member_tokens_limit" type="number" min="0"
                            @input="intInput('member_tokens_limit')" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="普通悬浮复制屏翻/次" prop="regular_float_copy_limit">
                        <el-input v-model.number="form.regular_float_copy_limit" type="number" min="0"
                            @input="intInput('regular_float_copy_limit')" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="会员悬浮复制屏翻/次" prop="member_float_copy_limit">
                        <el-input v-model.number="form.member_float_copy_limit" type="number" min="0"
                            @input="intInput('member_float_copy_limit')" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="普通快捷文字屏翻/次" prop="regular_quick_text_limit">
                        <el-input v-model.number="form.regular_quick_text_limit" type="number" min="0"
                            @input="intInput('regular_quick_text_limit')" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="会员快捷文字屏翻/次" prop="member_quick_text_limit">
                        <el-input v-model.number="form.member_quick_text_limit" type="number" min="0"
                            @input="intInput('member_quick_text_limit')" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <h2 style="margin-bottom:16px;">MO币兑换比例配置</h2>
                    <el-form-item label="10MO币兑换tokens数量" prop="redeem_tokens_per_10_momo">
                        <el-input v-model.number="form.redeem_tokens_per_10_momo" type="number" min="0"
                            @input="intInput('redeem_tokens_per_10_momo')" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="网页截图屏翻/张消耗" prop="web_capture_per_piece">
                        <el-input v-model.number="form.web_capture_per_piece" type="number" min="0"
                            @input="decimal1Input('web_capture_per_piece')" clearable :step="0.1"></el-input>
                    </el-form-item>
                    <el-form-item label="悬浮复制屏翻/次消耗" prop="float_copy_per_time">
                        <el-input v-model.number="form.float_copy_per_time" type="number" min="0"
                            @input="decimal1Input('float_copy_per_time')" clearable :step="0.1"></el-input>
                    </el-form-item>
                    <el-form-item label="快捷截图屏翻/张消耗" prop="quick_capture_per_piece">
                        <el-input v-model.number="form.quick_capture_per_piece" type="number" min="0"
                            @input="decimal1Input('quick_capture_per_piece')" clearable :step="0.1"></el-input>
                    </el-form-item>
                    <el-form-item label="快捷文字屏翻/次消耗" prop="quick_text_per_time">
                        <el-input v-model.number="form.quick_text_per_time" type="number" min="0"
                            @input="decimal1Input('quick_text_per_time')" clearable :step="0.1"></el-input>
                    </el-form-item>
                    <el-form-item label="跨应用精翻/分消耗" prop="accurate_minute_per_time">
                        <el-input v-model.number="form.accurate_minute_per_time" type="number" min="0"
                            @input="decimal1Input('accurate_minute_per_time')" clearable :step="0.1"></el-input>
                    </el-form-item>
                    <el-form-item label="跨应用快翻/分消耗" prop="quick_translate_minute_per_time">
                        <el-input v-model.number="form.quick_translate_minute_per_time" type="number" min="0"
                            @input="decimal1Input('quick_translate_minute_per_time')" clearable :step="0.1"></el-input>
                    </el-form-item>
                    <el-form-item label="漫画实时翻/分消耗" prop="comic_realtime_minute_per_time">
                        <el-input v-model.number="form.comic_realtime_minute_per_time" type="number" min="0"
                            @input="decimal1Input('comic_realtime_minute_per_time')" clearable :step="0.1"></el-input>
                    </el-form-item>

                    <el-form-item label="是否开启引导页" prop="enable_guide_page">
                        <el-switch v-model="form.enable_guide_page" :active-value="1" :inactive-value="0"></el-switch>
                    </el-form-item>

                </el-col>
            </el-row>


            <el-form-item>
                <el-button type="primary" :loading='load' @click="onSubmit">保存配置</el-button>
            </el-form-item>
        </el-form>
        <div style="margin: 0;">
            <el-form :model="form1" :rules="rules" ref="formRef1" @submit.native.prevent>
                <el-row>
                    <el-col :span="24">
                        <h2 style="margin-bottom:16px;">内购配置</h2>
                        <el-form-item label="">
                            <div v-for="(item, i) in list" :key="item.id"
                                style="margin-bottom:12px;display:flex;align-items:center;">
                                <span style="width:90px;display:inline-block;">{{ item.product_id }}</span>
                                <span style="margin:0 8px;">基础币</span>
                                <el-input v-model.number="item.base_coins" @input="val => onCoinInput('base', i, val)"
                                    type="number" min="0" style="width:100px;" size="small" clearable></el-input>
                                <span style="margin:0 8px;">赠送</span>
                                <el-input v-model.number="item.bonus_coins" @input="val => onCoinInput('bonus', i, val)"
                                    type="number" min="0" style="width:100px;" size="small" clearable></el-input>
                                <span style="margin-left:20px;color:#999;">到账：{{ item.base_coins + item.bonus_coins
                                    }}</span>
                                <el-button style="margin-left:20px;" type="primary" size="small"
                                    @click="submitEditCoinRule(item)">
                                    保存
                                </el-button>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
    </div>
</template>

<script>
import { getConfig } from "@/api/Transir";

import axios from "axios";
export default {
    name: "ConfigForm",
    data() {
        const checkInt = (rule, value, callback) => {
            if (value === undefined || value === null || value === "") {
                callback(new Error("必填项"));
            } else if (!/^\d+$/.test(String(value))) {
                callback(new Error("请输入非负整数"));
            } else {
                callback();
            }
        };
        const checkDecimal1 = (rule, value, callback) => {
            if (value === undefined || value === null || value === "") {
                callback(new Error("必填项"));
            } else if (!/^\d+(\.\d)?$/.test(String(value))) {
                callback(new Error("最多1位小数"));
            } else {
                callback();
            }
        };
        return {
            list: [],
            form: {
                regular_feature_minutes: 0,
                regular_photos_limit: 0,
                member_feature_minutes: 0,
                member_photos_limit: 0,
                regular_tokens_limit: 0,
                member_tokens_limit: 0,
                regular_float_copy_limit: 0,
                member_float_copy_limit: 0,
                regular_quick_text_limit: 0,
                member_quick_text_limit: 0,
                redeem_tokens_per_10_momo: 0,
                web_capture_per_piece: 0,
                float_copy_per_time: 0,
                quick_capture_per_piece: 0,
                quick_text_per_time: 0,
                accurate_minute_per_time: 0,
                quick_translate_minute_per_time: 0,
                comic_realtime_minute_per_time: 0,
                enable_guide_page: 0,
            },
            rules: {
                regular_feature_minutes: [{ required: true, validator: checkInt, trigger: "blur" }],
                regular_photos_limit: [{ required: true, validator: checkInt, trigger: "blur" }],
                member_feature_minutes: [{ required: true, validator: checkInt, trigger: "blur" }],
                member_photos_limit: [{ required: true, validator: checkInt, trigger: "blur" }],
                regular_tokens_limit: [{ required: true, validator: checkInt, trigger: "blur" }],
                member_tokens_limit: [{ required: true, validator: checkInt, trigger: "blur" }],
                regular_float_copy_limit: [{ required: true, validator: checkInt, trigger: "blur" }],
                member_float_copy_limit: [{ required: true, validator: checkInt, trigger: "blur" }],
                regular_quick_text_limit: [{ required: true, validator: checkInt, trigger: "blur" }],
                member_quick_text_limit: [{ required: true, validator: checkInt, trigger: "blur" }],
                redeem_tokens_per_10_momo: [{ required: true, validator: checkInt, trigger: "blur" }],
                 
                web_capture_per_piece: [{ required: true, validator: checkDecimal1, trigger: "blur" }],
                float_copy_per_time: [{ required: true, validator: checkDecimal1, trigger: "blur" }],
                quick_capture_per_piece: [{ required: true, validator: checkDecimal1, trigger: "blur" }],
                quick_text_per_time: [{ required: true, validator: checkDecimal1, trigger: "blur" }],
                accurate_minute_per_time: [{ required: true, validator: checkDecimal1, trigger: "blur" }],
                quick_translate_minute_per_time: [{ required: true, validator: checkDecimal1, trigger: "blur" }],
                comic_realtime_minute_per_time: [{ required: true, validator: checkDecimal1, trigger: "blur" }],
            },
            msg: '',
            msgType: 'success',
            load:false
        };
    },
    created() {
        this.getConfig();
        this.getConfig1();
    },
    methods: {
        decimal1Input(field) {
            let val = this.form[field];
            // 只允许正数和一位小数
            if (val === "" || val == null) return;
            val = String(val)
                .replace(/[^\d.]/g, "")           // 只保留数字和点
                .replace(/^\./g, "")              // 小数点不能开头
                .replace(/\.{2,}/g, ".")          // 不能有连续点
                .replace(".", "#").replace(/\./g, "").replace("#", ".") // 只第一个点
                .replace(/^(\d+)\.(\d).*$/, "$1.$2"); // 最多保留一位小数
            if (val !== "" && !isNaN(val)) {
                this.form[field] = parseFloat(val);
            }
        },
        onCoinInput(type, idx, val) {
            val = Number(val)
            if (val < 0 || isNaN(val)) val = 0; // 保证非负整数
            if (type === 'base') this.list[idx].base_coins = val
            if (type === 'bonus') this.list[idx].bonus_coins = val
        },
        async submitEditCoinRule(row) {
            if (!row.product_id) {
                this.$message.error('商品ID不能为空');
                return;
            }
            if (row.base_coins == null || isNaN(row.base_coins)) {
                this.$message.error('基础币数不能为空');
                return;
            }
            if (row.bonus_coins == null || isNaN(row.bonus_coins)) {
                this.$message.error('赠送币数不能为空');
                return;
            }
            try {
                let res = await axios.post('https://xiaoshuchengzhang.com/node/Transir/product-coin-rules/edit', {
                    product_id: row.product_id,
                    base_coins: row.base_coins,
                    bonus_coins: row.bonus_coins
                });
                if (res.data.code === 0) {
                    this.$message.success('修改成功');
                    // 可选：刷新list
                    this.getConfig1();
                } else {
                    this.$message.error(res.data.msg || '保存失败');
                }
            } catch (e) {
                this.$message.error('接口请求失败');
            }
        },
        intInput(field) {
            this.form[field] = String(this.form[field]).replace(/[^\d]/g, "");
            if (this.form[field] !== "") {
                this.form[field] = parseInt(this.form[field], 10);
            }
        },
        async getConfig() {
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });

            try {
                const {data} = await axios.get("https://xiaoshuchengzhang.com/node/Transir/config");
                loading.close();
                if (  data.data) {
                    // 把后端的秒数转为分钟（向下取整，或四舍五入都行）
                    this.form.regular_feature_minutes = Math.floor(data.data.regular_feature_minutes / 60);
                    this.form.member_feature_minutes = Math.floor(data.data.member_feature_minutes / 60);
                    this.form.regular_photos_limit = data.data.regular_photos_limit;
                    this.form.member_photos_limit = data.data.member_photos_limit;

                    this.form.regular_tokens_limit = data.data.regular_tokens_limit;
                    this.form.member_tokens_limit = data.data.member_tokens_limit;
                    this.form.regular_float_copy_limit = data.data.regular_float_copy_limit;
                    this.form.member_float_copy_limit = data.data.member_float_copy_limit;
                    this.form.regular_quick_text_limit = data.data.regular_quick_text_limit;
                    this.form.member_quick_text_limit = data.data.member_quick_text_limit;
                    this.form.redeem_tokens_per_10_momo = data.data.redeem_tokens_per_10_momo;
                    this.form.web_capture_per_piece = data.data.web_capture_per_piece;
                    this.form.float_copy_per_time = data.data.float_copy_per_time;
                    this.form.quick_capture_per_piece = data.data.quick_capture_per_piece;
                    this.form.quick_text_per_time = data.data.quick_text_per_time;
                    this.form.accurate_minute_per_time = data.data.accurate_minute_per_time;
                    this.form.quick_translate_minute_per_time = data.data.quick_translate_minute_per_time;
                    this.form.comic_realtime_minute_per_time = data.data.comic_realtime_minute_per_time;
                    this.form.enable_guide_page = data.data.enable_guide_page;

                }
            } catch (e) {
                this.msg = "获取配置失败";
                this.msgType = "error";
            }
        },
        async getConfig1() {
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            let res = await axios.post("https://xiaoshuchengzhang.com/node/Transir/product-coin-rules/list");
            loading.close();
            this.list = res.data.data
        },
        onSubmit() {
            this.$refs.formRef.validate(async valid => {
                if (valid) {
                    this.$confirm(
                        '确定要保存该配置吗？',
                        '二次确认',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }
                    ).then(async () => {
                        this.load =true
                        // 复制，转换为秒再提交
                        const payload = Object.assign({}, this.form, {
                            regular_feature_minutes: this.form.regular_feature_minutes * 60,
                            member_feature_minutes: this.form.member_feature_minutes * 60
                        });
                        try {
                            let res = await axios.post("https://xiaoshuchengzhang.com/node/Transir/updateConfig", payload);
                            let data = res.data;
                            if (data.code === 0) {
                                this.$message({
                                    message: 'success',
                                    type: 'success'
                                });
                            } else {
                                this.$message({
                                    message: 'error',
                                    type: 'error'
                                });
                            }
                        } catch {
                            this.$message({
                                message: 'error',
                                type: 'error'
                            });
                        }
                        this.load =false

                    }).catch(() => {
                        this.load =false

                        this.msg = "已取消操作";
                        this.msgType = "error";
                    });
                }
            });
        }

    }

};
</script>

<style scoped>
.config-wrapper {
    background: #fff;
    border-radius: 8px;
    padding: 28px 18px 38px 18px;
    margin: 0 auto;
    max-width: 1000px;
}

.notice {
    margin-top: 20px;
    font-size: 15px;
    padding: 10px 14px;
    border-radius: 8px;
}

.success {
    background: #e5f6ec;
    color: #15a167;
}

.error {
    background: #ffdbe9;
    color: #cd2323;
}
</style>
